package com.czy.owner.ui.hotshop;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.czy.owner.R;
import com.czy.owner.adapter.BrandRecommendAdapter;
import com.czy.owner.adapter.HotClassifyPagerAdapter;
import com.czy.owner.adapter.HotShopClassifyLeftAdapter;
import com.czy.owner.adapter.HotShopClassifyRightAdapter;
import com.czy.owner.api.HotShopClassifyApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.HotShopClassifyModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.DividerGridItemDecoration;
import com.czy.owner.widget.ZoomOutPageTransformer;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
/**
 * Created by asus
 * 平台商品分类样式
 * platformType
 */
public class HotShopClassifyActivity2 extends BaseActivity {

    private boolean isBannerStart = true;
    private boolean isStop;
    private Handler mHandler = new Handler();

    /**
     * 图片自动轮播Task
     */
    private Runnable mImageTimerTask = new Runnable() {
        @Override
        public void run() {
            vpActivityZone.setCurrentItem(vpActivityZone.getCurrentItem() + 1);
            if (!isStop) {  //if  isStop=true   //当你退出后 要把这个给停下来 不然 这个一直存在 就一直在后台循环
                mHandler.postDelayed(mImageTimerTask, 3000);
            }

        }
    };
    private BrandRecommendAdapter recommendAdapter;

    /**
     * 图片滚动任务
     */
    private void startImageTimerTask() {
        // 图片滚动
        mHandler.postDelayed(mImageTimerTask, 100);
    }

    /**
     * 停止图片滚动任务
     */
    private void stopImageTimerTask() {
        isStop = true;
        mHandler.removeCallbacks(mImageTimerTask);
    }


    @BindView(R.id.rv_classify_left)
    RecyclerView rvClassifyLeft;
    @BindView(R.id.rv_classify_right)
    RecyclerView rvClassifyRight;
    private ArrayList<HotShopClassifyModel> classifyLeftModels = new ArrayList<>();
    private ArrayList<HotShopClassifyModel.SubsBean> classifyRightModels = new ArrayList<>();
    private ArrayList<HotShopClassifyModel.BrandRecommendListBean> brandRecommendList = new ArrayList<>();
    private ArrayList<HotShopClassifyModel.ActivityZoneListBean> activityZoneList = new ArrayList<>();
    private HotShopClassifyLeftAdapter classifyLeftAdapter;
    private HotShopClassifyRightAdapter classifyRightAdapter;
    private static int CLASSIFY_TYPE = 0;
    private static final int PLATFORM_TYPE = 0;
    private int goodsType = 0;
    private String goodsActivityId;
    private ViewPager vpActivityZone;
    private RecyclerView rvHotClassify;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_hot_shop_classify2;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        initData();
        initLeftClassify();
        initRightClassify();

    }

    private void initData() {
        goodsActivityId = getIntent().getStringExtra("goodsActivityId");
        goodsType = getIntent().getIntExtra("goodsType", PLATFORM_TYPE);
        String storeId = "0";
        if (goodsType != PLATFORM_TYPE) {
            storeId = SharedPreferencesUtils.getParam(HotShopClassifyActivity2.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "";
        }
        HotShopClassifyApi hotShopClassifyApi = new HotShopClassifyApi(new HttpOnNextListener<List<HotShopClassifyModel>>() {
            @Override
            public void onNext(List<HotShopClassifyModel> models) {
                setLeftAdapter(models);
            }


            @Override
            public void onError(Throwable e) {
                super.onError(e);

            }
        }, this, goodsType);
        hotShopClassifyApi.setSession(UserHelper.getInstance().getSession(this));
        hotShopClassifyApi.setStoreId(storeId);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(hotShopClassifyApi);
    }

    //左侧一级分类
    private void initLeftClassify() {
        classifyRightModels.clear();
        classifyLeftAdapter = new HotShopClassifyLeftAdapter(this, 0);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvClassifyLeft.setAdapter(classifyLeftAdapter);
        rvClassifyLeft.setLayoutManager(linearLayoutManager);

        rvClassifyLeft.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        classifyLeftAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object o) {
                classifyLeftAdapter.updateSelectPosition(position);
                setRightAdapter(position);
            }
        });

    }

    //右侧二级
    private void initRightClassify() {


        classifyRightAdapter = new HotShopClassifyRightAdapter(this);
        GridLayoutManager girdLayoutManager = new GridLayoutManager(this, 3);

        girdLayoutManager.setSpanSizeLookup(classifyRightAdapter.obtainTipSpanSizeLookUp());
        rvClassifyRight.setAdapter(classifyRightAdapter);
        rvClassifyRight.setLayoutManager(girdLayoutManager);
        //TODO 新增热门商品与轮播
        classifyRightAdapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                View view = LayoutInflater.from(HotShopClassifyActivity2.this).inflate(R.layout.header_classify_hot_shop, null);
                vpActivityZone = (ViewPager) view.findViewById(R.id.vp_activity_zone);
                rvHotClassify = (RecyclerView) view.findViewById(R.id.rv_hot_classify);
                vpActivityZone.setPageTransformer(true, new ZoomOutPageTransformer());
                vpActivityZone.setVisibility(View.GONE);
                rvHotClassify.setVisibility(View.GONE);
                recommendAdapter = new BrandRecommendAdapter(HotShopClassifyActivity2.this);
                GridLayoutManager girdLayoutManager = new GridLayoutManager(HotShopClassifyActivity2.this, 3);
                girdLayoutManager.setSpanSizeLookup(recommendAdapter.obtainTipSpanSizeLookUp());
                rvHotClassify.setAdapter(recommendAdapter);
                rvHotClassify.setLayoutManager(girdLayoutManager);
                rvHotClassify.addItemDecoration(new DividerGridItemDecoration(HotShopClassifyActivity2.this));
                recommendAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position, Object o) {
                        HotShopClassifyModel.BrandRecommendListBean recommendListBean = (HotShopClassifyModel.BrandRecommendListBean) o;
                        if (!recommendListBean.isGroup()){

                        }
                    }
                });
                return view;
            }

            @Override
            public void onBindView(View headerView) {

            }
        });

        classifyRightAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object o) {
                HotShopClassifyModel.SubsBean subsBean = (HotShopClassifyModel.SubsBean) o;
                Intent intent = new Intent(HotShopClassifyActivity2.this, GoodsListActivity.class);
                intent.putExtra("fromType", CLASSIFY_TYPE);
                intent.putExtra("categoryId", subsBean.getCategoryId());
                intent.putExtra("goodsType", getIntent().getIntExtra("goodsType", PLATFORM_TYPE));
                intent.putExtra("title", subsBean.getCategoryName());
                intent.putExtra("mFromType",Constants.GOODSSOURCE_STORE);
                intent.putExtra("mFromTypeId", "0");
                if (!TextUtils.isEmpty(goodsActivityId)) {
                    intent.putExtra("goodsActivityId", goodsActivityId);
                }


                startActivity(intent);
            }
        });


    }

    @Override
    protected void updateViews() {

    }

    @OnClick({R.id.img_back, R.id.ll_goods_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.ll_goods_search:
                Intent intent = new Intent(HotShopClassifyActivity2.this, GoodsSearchHistoryActivity.class);
                intent.putExtra("goodsType", goodsType);
                startActivity(intent);
                break;
        }
    }

    private void setLeftAdapter(List<HotShopClassifyModel> models) {
        classifyLeftModels.clear();
        classifyLeftModels.addAll(models);
        classifyLeftAdapter.addAll(classifyLeftModels);
        if (models.size() > 0)
            setRightAdapter(0);
    }

    private void setRightAdapter(final int selectPosition) {
        //TODO 轮播初始化
        stopImageTimerTask();
        isBannerStart = true;
        isStop = false;
        classifyRightModels.clear();
        classifyRightAdapter.clear();
        brandRecommendList.clear();
        recommendAdapter.clear();
        vpActivityZone.setVisibility(classifyLeftModels.get(selectPosition).getActivityZoneList().size() > 0 ? View.VISIBLE : View.GONE);
        HotClassifyPagerAdapter hotClassifyPagerAdapter = new HotClassifyPagerAdapter(this, classifyLeftModels.get(selectPosition).getActivityZoneList());
        vpActivityZone.setOffscreenPageLimit(classifyLeftModels.get(selectPosition).getActivityZoneList().size());
        vpActivityZone.setAdapter(hotClassifyPagerAdapter);
        if (classifyLeftModels.get(selectPosition).getActivityZoneList().size() > 1) {
            vpActivityZone.setCurrentItem(1);
            if (isBannerStart) {
                startImageTimerTask();
                isBannerStart = false;
            }

        }

        //推荐品牌
        List<HotShopClassifyModel.BrandRecommendListBean> brandList = classifyLeftModels.get(selectPosition).getBrandRecommendList();
        rvHotClassify.setVisibility(brandList.size() >=3 ? View.VISIBLE : View.GONE);
        if (brandList.size() >= 3) {
            HotShopClassifyModel.BrandRecommendListBean bean = new HotShopClassifyModel.BrandRecommendListBean();
            bean.setGroup(true);
            for (int k = 0; k < brandList.size(); k++) {
                brandList.get(k).setGroup(false);
            }
            brandRecommendList.add(bean);
            brandRecommendList.addAll(brandList);
        }
        recommendAdapter.addAll(brandRecommendList);
        recommendAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object o) {
                HotShopClassifyModel.BrandRecommendListBean recommendListBean = (HotShopClassifyModel.BrandRecommendListBean) o;
                if (!recommendListBean.isGroup()){
                    Intent intent = new Intent(HotShopClassifyActivity2.this, GoodsListActivity.class);
                    intent.putExtra("fromType", CLASSIFY_TYPE);
                    intent.putExtra("categoryId",0);
                    intent.putExtra("goodsType", getIntent().getIntExtra("goodsType", PLATFORM_TYPE));
                    intent.putExtra("title", recommendListBean.getChName());
                    intent.putExtra("goodsBrandId", recommendListBean.getGoodsBrandId());
                    intent.putExtra("mFromType",Constants.GOODSSOURCE_STORE);
                    intent.putExtra("mFromTypeId", "0");
                    if (!TextUtils.isEmpty(goodsActivityId)) {
                        intent.putExtra("goodsActivityId", goodsActivityId);
                    }
                    startActivity(intent);
                }
            }
        });

        List<HotShopClassifyModel.SubsBean> subs = classifyLeftModels.get(selectPosition).getSubs();//二级
        for (int j = 0; j < subs.size(); j++) {
            HotShopClassifyModel.SubsBean subsBean = subs.get(j);
            subsBean.setGroup(true);
            classifyRightModels.add(subsBean);
            for (int k = 0; k < subsBean.getSubs().size(); k++) {
                subsBean.getSubs().get(k).setGroup(false);
                classifyRightModels.add(subsBean.getSubs().get(k));
            }

        }

        classifyRightAdapter.addAll(classifyRightModels);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopImageTimerTask();
    }
}
